package main

import (
	"encoding/json"
	"fmt"
	"gopl.io/ch4/github"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strings"
)

const IssuesURL = "https://api.github.com/search/issues"

func main() {
	terms := os.Args[1:]
	q := url.QueryEscape(strings.Join(terms, " "))
	resp, err := http.Get(IssuesURL + "?q=" + q)
	defer resp.Body.Close()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Get error: %v\n", err)
		os.Exit(1)
	}
	if resp.StatusCode != http.StatusOK {
		fmt.Fprintf(os.Stderr, "Response error: %v\n", err)
		os.Exit(1)
	}
	var result github.IssuesSearchResult
	body, _ := ioutil.ReadAll(resp.Body)
	//fmt.Printf("Respose result is: %b\n", body)
	if err := json.Unmarshal(body, &result); err != nil {
		fmt.Fprintf(os.Stderr, "Response unmashal error: %v\n", err)
	}

	for _, item := range result.Items {
		fmt.Printf("#%-5d %9.9s %.55s\n",
			item.Number, item.User.Login, item.Title)
	}

}
